package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.exception.ServiceErrorCode;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.CouponService;
import cn.com.connext.scrm.service.mapper.OrderService;
import cn.com.connext.scrm.utils.ExcelUtil;
import cn.com.connext.scrm.web.rest.req.OrderQueryExcelReq;
import cn.com.connext.scrm.web.rest.req.OrderQueryReq;
import com.alibaba.fastjson.JSON;
import com.connext.common.exception.ServiceException;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/shopping/coupon")
public class CouponUploadResource {

    private final Logger log = LoggerFactory.getLogger(CouponUploadResource.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private CouponService couponService;

    final static String fileName = "有赞卷数据模板excel.xls";

    @PostMapping("/addCoupon")
    @ApiOperation("通过上传excel添加有赞卷")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public JsonResult addCoupon(MultipartFile file,@RequestParam("productId") String productId) {
        if (file == null || file.isEmpty() || StringUtils.isEmpty(productId)) {
            throw new ServiceException(ServiceErrorCode.ILLEGAL_ARGUMENT_ERROR_ANALYSIS_EXCEL);
        }
        return couponService.addCoupon(file,productId);
    }

    @GetMapping("/export/order-item-excel")
    @ApiOperation("销售明细导出报表")
    public JsonResult exportOrderItemExcel(HttpServletResponse response, OrderQueryExcelReq req) {
        JsonResult jsonResult = new JsonResult();
        log.info("销售明细导出报表，入参: {}", JSON.toJSONString(req));
        try {
            Workbook workbook = orderService.exportOrderItemExcel(req);
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                "attachment;filename=\"" + new String("订单明细".getBytes(), "iso-8859-1")
                    + System.currentTimeMillis() + ".xls\"");
            response.setHeader("Connection", "close");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            log.error("# [订单明细]报表导出失败,msg = {}", e.getMessage(), e);
            jsonResult.setState(1);
            jsonResult.setMessage("[订单明细]报表导出失败");
            return jsonResult;
        }
        jsonResult.setState(0);
        jsonResult.setData("[销售明细]报表导出成功");
        return jsonResult;
    }

    /**
     *
     */
    @GetMapping(value = "/download/coupon-item-excel")
    @ApiOperation("下载excel模板")
    public void exportCouponItemExcel(HttpServletResponse response) throws IOException {
        JsonResult jsonResult = new JsonResult();
        log.info("下载有赞卷样板，入参: {}");

        HSSFWorkbook workbook = getTemplateByCode();
        // 创建一个工作薄
        ExcelUtil.exportExcel(response, workbook, fileName);
    }

    private HSSFWorkbook getTemplateByCode() {
        long t1 = System.currentTimeMillis();
        final String targetCustomersExcelTemplate = "targetCustomersExcelTemplate";
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet1 = workbook.createSheet("sheet");
        createTitle(workbook, sheet1);
        long t2 = System.currentTimeMillis();
        log.debug("耗时={}ms", (t2 - t1));
        return workbook;
    }

    private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet) {
        HSSFRow row = sheet.createRow(0);
        sheet.setColumnWidth(3, 30 * 256);
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFDataFormat dataFormat = workbook.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));
        HSSFFont font = workbook.createFont();
        style.setFont(font);
        HSSFCell cell0;
        cell0 = row.createCell(0);
        cell0.setCellValue("id");
        cell0.setCellStyle(style);

        HSSFCell cell1 = row.createCell(1);
        cell1.setCellValue("有赞卷名字");
        cell1.setCellStyle(style);

        HSSFCell cell2 = row.createCell(2);
        cell2.setCellValue("优惠卷有效期");
        cell2.setCellStyle(style);

        HSSFCell cell3 = row.createCell(3);
        cell3.setCellValue("优惠卷路径");
        cell3.setCellStyle(style);
    }
}
